<template>
	<view class="core-tabs-box">
		<slot name="left"> </slot>
		<scroll-view :scroll-x="true" class="scroll-view" enable-flex :scroll-left="state.scrollLeft"
			:scroll-with-animation="true">
			<view v-for="item, index in props.list" :key="index"
				:class="['tab-item-box', { 'on': index === state.current }]" @click="hanldeClickTab(item, index)">
				{{ item[props.keyNname] }}
			</view>
		</scroll-view>
		<slot name="right"></slot>
	</view>
</template>
<script setup lang="ts">
	import { reactive, watch, getCurrentInstance } from 'vue';

	const instance = getCurrentInstance();

	const props = withDefaults(defineProps<{
		current : number,
		keyNname : string,
		list : Array<any>,
	}>(), {
		current: 0,
		keyNname: 'name',
		list: () => [],
	});

	const emit = defineEmits(['hanldeClickTab'])

	const state = reactive<{
		arr : Array<any>,
		lineLeft : number,
		current : number,
		scrollLeft : number,
	}>({
		arr: [],
		lineLeft: 0,
		current: props.current,
		scrollLeft: 0,
	})

	watch(() => props.list, (newVal : any) => {
		if (newVal) {
			state.current = 0;
			calculationLineLeftNum();
		}
	})

	const calculationLineLeftNum = () => {
		const query = uni.createSelectorQuery().in(instance.proxy);
		query.selectAll('.tab-item-box')
			.boundingClientRect((rect : any) => {
				state.arr = [];
				rect.forEach((item : any) => {
					state.arr.push({
						width: item.width
					});
				});
			})
			.exec()
	}

	const hanldeClickTab = (item : any, index : number) => {
		if (state.current != index) {
			state.current = index;
			let scrollLeft = 0;
			for (let i = 0; i < index - 1; i++) {
				scrollLeft += state.arr[i].width
			};
			state.scrollLeft = scrollLeft;
			emit('hanldeClickTab', item)
		}
	}
</script>

<style lang="scss" scoped>
	@import "./coreshop-tabs.scss";
</style>